﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using XJay.DB.Model;
using XJay.Job.BirthdayEmail.Dto;
using XJay.Scheduler.Common.Helper;
using XJay.Scheduler.Common.Helper.Mail;

namespace XJay.Job.BirthdayEmail
{
    public class BirthdayEmailJob : BaseJob 
    {
        private readonly SmtpHelper _smtpHelper;
        public BirthdayEmailJob()
        {
            _smtpHelper = new SmtpHelper("info@easybom.com", "easy252525", "smtpout.secureserver.net", 25, "easybom");
        }
        public override async Task TodoJob(IJobExecutionContext context)
        {
            try
            {
                await ScanBirthdayMail((list) => {

                    foreach (var item in list)
                    {
                        MailMessage mailMessage = new();
                        mailMessage.Subject = "";
                        mailMessage.IsBodyHtml = true;
                        var values = new NameValueCollection
                        {
                            { "Name", item.Name }
                        };
                        mailMessage.Body = TemplateHelper.Build(item.TemplateContent, values);
                        context.Info("正在发送");
                        _smtpHelper?.Send("2320496944@qq.com", mailMessage.Subject, mailMessage.Body, mailMessage.IsBodyHtml);
                        context.Info("已成功发送");
                    }

                });
            }
            catch (Exception ex)
            {
                await jobContext.InfoAsync(ex.ToString());
                throw;
            }

        }
        /// <summary>
        /// 每次扫描要做的事
        /// </summary>
        /// <param name="action"></param>
        /// <param name="takeCount"></param>
        /// <returns></returns>
        public async Task ScanBirthdayMail(Action<List<MailDto>> action,int takeCount = 1000)
        {
            int tempId = 0;
            var dateTime = DateTime.Now.Date;
            while (true)
            {
                var list = await XJaySqlClient.Queryable<App_BirthdayMail>().LeftJoin<App_MailTemplate>((a, b) => a.TemplateID == b.TID)
                .Where(p => p.SendTime == dateTime)
                .Select((p, b) => new MailDto
                {
                    Id = p.EID,
                    Name = p.Name,
                    SendAddressee = p.Addressee,
                    TemplateContent = b.TemplateContent
                }).Take(takeCount).OrderBy(p=>p.Id).ToListAsync();
                if(list.Count<1)
                {
                    await jobContext.InfoAsync("生日表扫描结束！！！Job执行结束");
                }
                await jobContext.InfoAsync($"当前从ID:{tempId}开始扫描了{list.Count}条数据进行处理");
                tempId = list.LastOrDefault()?.Id ?? 0;
                action(list);
            }
        }
    }
}
